﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static org.apache.zookeeper.ZooDefs;

namespace Coldairarrow.Business.Interface
{
    public class LX_FBAShipmentInterfaceBusiness : LXInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption LX_Query;
        //获取亚马逊店铺
        public LX_SellerInterfaceBusiness sellerInterfaceBusiness;
        public LX_FBAShipmentInterfaceBusiness()
        {
            this.InterfaceName = "FBA货件";
            //索引字段
            this.MapFields = GetMapField("LX_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            LX_Query = this.interfaceOption.Where(x => x.OperateType == "LX_Query").First();
            //获取亚马逊店铺
            sellerInterfaceBusiness = new LX_SellerInterfaceBusiness();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, LX_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, LX_QueryEventArgs queryEventArgs)
        {
            try
            {
                //同一个seller_id授权的店铺任取一个sid请求报表数据即可
                List<string> sellers = sellerInterfaceBusiness.Query<Seller>(sellerInterfaceBusiness.LX_Query, SqlDb).Select(x => x.sid).ToList();
                queryEventArgs.CustomData = String.Join(",", sellers);
                //获取appId
                var key = JObject.Parse(LX_Query.TargetLoginData);
                queryEventArgs.UrlQuery.AppId = key["appId"].Value<string>();
                queryEventArgs.UrlQuery.AppSecret = key["appSecret"].Value<string>();
                queryEventArgs.UrlQuery.OL_Key = key["OL_Key"].Value<string>();
                //获取token
                queryEventArgs.UrlQuery.Token = GetToken(queryEventArgs.UrlQuery.OL_Key);//one_link
                                                                                         //queryEventArgs.UrlQuery.Token = GetToken(queryEventArgs.UrlQuery.AppId, queryEventArgs.UrlQuery.AppSecret);//领星
                                                                                         //设置单次查询的页面数量
                queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "length").First().SourceField.ToInt();
                //设置需要查询多久之前的数据
                queryEventArgs.Page.Total = queryEventArgs.APINodes.Where(x => x.TargetField == "start_date").First().Notes.ToInt();
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, LX_QueryEventArgs queryEventArgs)
        {
            //日期大于当日停止循环
            if (!string.IsNullOrEmpty(queryEventArgs.UrlQuery.Token) && DateTime.Now.AddMonths(queryEventArgs.Page.Total + 1) <= DateTime.Now)
            {
                //获取请求的数据
                ReqDTO_A data = new ReqDTO_A();
                //批准日期开始时间，闭区间，格式：Y-m-d
                data.start_date = DateTime.Now.AddMonths(queryEventArgs.Page.Total).ToString("yyyy-MM-dd");
                //批准日期结束时间【时间间隔最长不得超过90天】，闭区间，格式：Y-m-d
                //data.end_date = DateTime.Now.AddMonths(queryEventArgs.Page.Total + 1).ToString("yyyy-MM-dd");
                data.end_date = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd");
                data.length = queryEventArgs.Page.PageSize;
                data.offset = queryEventArgs.Page.PageIndex;
                data.sids = queryEventArgs.CustomData.ToString();
                queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
                var reqData = JObject.Parse(queryEventArgs.reqData);
                //获取所有json节点的信息
                var nodes = queryEventArgs.APINodes.Where(x => x.ParentNO == "TOP" && x.OptionId == LX_Query.Id);
                //需要将请求的数据拼接到url中，先转换成字典
                Dictionary<string, object> reqKeyValue = new Dictionary<string, object>();
                foreach (var item in nodes)
                {
                    if (!reqData[item.TargetField].ToString().IsNullOrEmpty())
                    {
                        reqKeyValue.Add(item.TargetField, reqData[item.TargetField].ToString());
                    }
                }
                //获取编码后的URL
                string url = GetEncodeUrl(LX_Query.TargetUrl, queryEventArgs.UrlQuery.Token, queryEventArgs.UrlQuery.AppId, reqKeyValue);
                queryEventArgs.HttpClient.Url = url;
            }
            else
            {
                queryEventArgs.Page.Complete = true;
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, LX_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                FBAShipmentDTO result = (FBAShipmentDTO)JsonConvert.DeserializeObject<FBAShipmentDTO>(queryEventArgs.ResultStr);
                if (result.message == "success")
                {
                    queryEventArgs.Success = true;
                }
                else
                { queryEventArgs.Success = false; }

                if (result.data.list.Count < queryEventArgs.Page.PageSize)
                {
                    //页数重置
                    queryEventArgs.Page.Complete = true;
                    if (result.data.list.Count > 0) queryEventArgs.Rows = result.data.list;

                }
                else
                {
                    //查询下一页
                    queryEventArgs.Page.PageIndex += queryEventArgs.Page.PageSize;
                    queryEventArgs.Rows = result.data.list;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<FBAShipment> QQ = await this.QueryAsync<FBAShipment>(this.LX_Query, SqlDb);
            var ww1 = QQ.Where(x => x.item_list.Where(y => y.shipment_plan_list.Count > 1).Count() > 0).ToList();
            var ww = QQ.GroupBy(r => r.id).Select(g => g.FirstOrDefault()).ToList();
        }

        /// <summary>
        /// 获取参数编译后的URL
        /// </summary>
        /// <param name="url"></param>
        /// <param name="access_token"></param>
        /// <param name="app_key"></param>
        /// <param name="reqData"></param>
        /// <returns></returns>
        public string GetEncodeUrl(string url, string access_token, string app_key, Dictionary<string, object> reqKeyValue)
        {

            //获取当前时间戳
            int tmeStamp = DateTime.Now.ToUnixTimeStamp();
            reqKeyValue.Add("access_token", access_token);
            reqKeyValue.Add("app_key", app_key);
            reqKeyValue.Add("timestamp", tmeStamp);
            reqKeyValue = reqKeyValue.OrderBy(x => x.Key).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            StringBuilder sb = new StringBuilder();
            foreach (var item in reqKeyValue)
            {
                sb.Append(item.Key);
                sb.Append("=");
                sb.Append(item.Value);
                sb.Append("&");
            }
            //移除左后一个&连接符号
            sb.Remove(sb.Length - 1, 1);
            string sign = sb.ToString();
            //MD5加密
            sign = sign.ToMD5String().ToUpper();
            //AES加密
            sign = AESHelper.AESEncrypt(sign, app_key);
            //UrlEncode编码
            sign = WebUtility.UrlEncode(sign);
            string EncodeUrl = $"{url}?access_token={access_token}&app_key={app_key}&timestamp={tmeStamp}&sign={sign}";
            return EncodeUrl;
        }

        /// <summary>
        /// 通过form-data的形式发送参数请求获取TOKEN
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public string GetToken(string appId, string appSecret)
        {
            //1.获取Token
            HttpClient httpClient = new HttpClient();
            httpClient.Url = "https://openapi.lingxing.com/api/auth-server/oauth/access-token";
            Header header = new Header();
            httpClient.ContentType = "multipart/form-data; boundary=POWTEK\r\n";
            // 设置请求参数
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("appId", appId);
            data.Add("appSecret", appSecret);
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, string> kvp in data)
            {
                sb.AppendFormat("--POWTEK\r\n");
                sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\"\r\n", kvp.Key);
                sb.AppendFormat("\r\n{0}\r\n", kvp.Value);
            }
            sb.AppendFormat("--POWTEK--\r\n");
            httpClient.Content = sb.ToString();
            string r = httpClient.Request();
            LX_Token sysReportResul1t = (LX_Token)JsonConvert.DeserializeObject<LX_Token>(r);
            if (sysReportResul1t.code == "200" && sysReportResul1t.msg == "OK")
            {
                return sysReportResul1t.data.access_token;

            }
            else
            {
                return "";

            }
        }
        /// <summary>
        /// 通过ONE_LINK提供的接口发送请求获取TOKEN
        /// </summary>
        /// <param name="ol_key"></param>
        /// <returns></returns>
        public string GetToken(string ol_key)
        {
            //1.获取Token
            HttpClient httpClient = new HttpClient();
            httpClient.Method = "GET";
            // 设置请求参数
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("https://pms.powtek.net/api/workflow/hooks/NjZlMGVlZTY5OTcwNGQzZTk0ZTE0YTVk");
            sb.AppendFormat($"?key={ol_key}");
            httpClient.Url = sb.ToString();
            string sysReportResul1t = httpClient.Request();
            if (!sysReportResul1t.IsNullOrEmpty())
            {
                return sysReportResul1t;

            }
            else
            {
                return "";

            }
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
